package com.leyou.gateway.task;

import com.leyou.gateway.client.AuthClient;
import com.leyou.gateway.config.JwtProperties;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 配置定时任务
 *
 * @author chao
 */
@Slf4j
@Component
public class AppTokenHolder {
    /**
     * token刷新间隔
     */
    private static final long TOKEN_REFRESH_INTERVAL = 86400000L;
    /**
     * token获取失败后重试的间隔
     */
    private static final long TOKEN_RETRY_INTERVAL = 10000L;
    @Getter
    private String token;
    @Autowired
    private AuthClient authClient;
    @Autowired
    private JwtProperties jwtProperties;

    @Scheduled(fixedDelay = TOKEN_REFRESH_INTERVAL)
    public void loadTokenTask() throws InterruptedException {
        // 模拟实时监控
        while (true) {
            try {
                log.info("【乐优网关】去授权中心申请token开始");
                token = authClient.authorization(jwtProperties.getApp().getId(),
                        jwtProperties.getApp().getSecret());
                log.info("【乐优网关】去授权中心申请token成功");
                // 如果申请成功跳出循环
                break;
            } catch (Exception e) {
                log.error("【乐优网关】去授权中心申请token失败：{}", e.getMessage());
            }
            Thread.sleep(TOKEN_RETRY_INTERVAL);
        }
    }
}
